package hash;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 18.四数之和
 * User: Li_yizYa
 * Date: 2025—04—07
 * Time: 19:34
 */
public class Solution8 {
    public static void main(String[] args) {
        int[] nums = {1,0,-1,0,-2,2};
        List<List<Integer>> ret = fourSum(nums, 0);
        for (List<Integer> list : ret) {
            System.out.print("[ ");
            for (int i : list) {
                System.out.print(i + " ");
            }
            System.out.println("]");
        }
    }

    private static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return ret;
        }
        Arrays.sort(nums);
        // nums[i] + nums[j] + nums[left] + nums[right]
        for (int i = 0; i < nums.length; i++) {
            // 剪枝
            if (nums[i] > target && nums[i] >= 0) {
                return ret;
            }
            // 去重
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            for (int j = i + 1; j < nums.length; j++) {
                // 剪枝
                if (nums[i] + nums[j] > target && nums[j] >= 0) {
                    break;
                }

                // 去重
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }

                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        ret.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right - 1]) {
                            right--;
                        }
                        left++;
                        right--;
                    }
                }
            }
        }
        return ret;
    }
}
